package com.itsitio.registeradmin.web.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.itsitio.registeradmin.dto.BranchDTO;
import com.itsitio.registeradmin.model.Branch;
import com.itsitio.registeradmin.model.Company;
import com.itsitio.registeradmin.model.UserRegistration;
import com.itsitio.registeradmin.service.BranchSrv;
import com.itsitio.registeradmin.service.CompanySrv;
import com.itsitio.registeradmin.service.UserRegistrationSrv;
import com.itsitio.registeradmin.web.UserContext;

@Controller
@SessionAttributes({"userContext"})
public class BranchController extends BaseController {

	private static final Logger log = LoggerFactory.getLogger(BranchController.class);
		
	@Autowired
	private UserRegistrationSrv userRegSrv;
	
	@Autowired
	private CompanySrv companySrv;
	
	@Autowired
	private BranchSrv branchSrv;
	

	/**
	 * Muestra la pantalla de Sucursal: 
	 * - formulario cargado con los datos de la sucursal que cargo el usuario al registrarse
	 * - lista de empresas que tienen nombre parecido 
	 * a la que cargo el usuario y/o cuil = al cargado por el usuario. 
	 * @param model
	 * @param userRegId
	 * @return
	 */
	@RequestMapping("/showBranchSection.html")
	public String showBranchSection(Model model, @RequestParam Integer userRegId, @RequestParam Integer companyId, @ModelAttribute UserContext userContext) {

		if(log.isDebugEnabled()) {
			  log.debug("Begin with userRegId="+userRegId+", companyId="+companyId);
		}
		
		List<Branch> branchList = null;
		
		BranchDTO branchDTO = new BranchDTO();
		
		UserRegistration userRegistration = userRegSrv.get(userRegId);
		
		//carga el formulario de nueva sucursal
		if(userRegistration != null){

			branchDTO.setAddress(userRegistration.getBranchAddress());
			branchDTO.setCity(userRegistration.getBranchCity());
			if(userRegistration.getBranchProvince() != null){
				branchDTO.setProvince(userRegistration.getBranchProvince().getName());
				branchDTO.setProvinceId(userRegistration.getBranchProvince().getId());
			}
			branchDTO.setZipCode(userRegistration.getBranchZipPostal());
			branchDTO.setPhone(userRegistration.getBranchPhone());			
		}

		//buscamos la empresa por el id
		Company company = companySrv.getCompanyById(companyId);
		branchList = branchSrv.getBranchListByCompany(company);
		
		if (branchList != null) {
			if(log.isDebugEnabled())
				log.debug("branchList.size="+branchList.size());
		} else {
			if(log.isWarnEnabled())
				log.warn("branchList is NULLLLL");		
		}
	    
		model.addAttribute("newBranch", branchDTO);
		model.addAttribute("branchList", branchList);
		model.addAttribute("userRegId", userRegId);		
		model.addAttribute("companyId", companyId);	
		model.addAttribute("companyId", companyId);
		model.addAttribute("provinceList",userRegistration.getCompanyCountry().getProvinces());
		
		// bread crumbs
		userContext.setTradeName(company.getTradeName());
		userContext.setType(company.getCompanyType() != null ? company.getCompanyType().getName() : "");
		userContext.setWebsite(company.getWebsite());
		
		return forward("branch/branchSection", model);
	}
	

	/**
	 * @param model
	 * @param action
	 * @return
	 */
	@RequestMapping("/updateBranch.html")
	public String updateBranch(Model model, @RequestParam String nextStep,
			@RequestParam Integer userRegId, @RequestParam Integer companyId,@RequestParam Integer selectedBranch,
			@RequestParam String branchAddress, @RequestParam String branchCity, 
			@RequestParam Integer branchProvince2,@RequestParam String branchZipPostal, @RequestParam String branchPhone) {		
		
		Company company = null;
		Branch newBranch = null;
		
		Integer branchId = selectedBranch;
		if(nextStep.equalsIgnoreCase("actualizar")){
			
			branchSrv.updateBranchWithUserRegistrationData(selectedBranch,
					branchAddress, branchCity, branchProvince2,branchZipPostal, branchPhone);
			
		} else if (nextStep.equalsIgnoreCase("nuevaSucursal")){
			
			newBranch = branchSrv.createBranchFromUserRegistration(companyId, 
					branchAddress, branchCity, branchProvince2,branchZipPostal, branchPhone);
			
			//como la sucursal es nueva, tenemos que obtener el id de la NUEVA Sucursal.
			branchId = newBranch.getId();			
		}
		
		return "redirect:/showUserSection.html?userRegId="+userRegId+"&branchId="+branchId;
	}
}
